////
////  CDIMService.swift
////  CandyDate
////
////  Created by zolobdz on 2017/9/27.
////  Copyright © 2017年 HeChao. All rights reserved.
////
//
//import Foundation
//import NIMSDK
//import UserNotifications
//import AVKit
//
//
////let CDIMStrangeLockHeader = "*-cd_stranger_lock-*"
//let CDIMCustomNotificationTypeDeleteFriend = "100" // 删除好友
//
//class CDIMService: NSObject {
//    
//    static let shared = CDIMService()
//    private override init() {}
//    
//    lazy var currentNetCallID: UInt64 = 0
//    
//    func startService() {
//        #if APPSTORE
//            NIMSDK.shared().register(withAppID: "010d0e7d80993a4f353e69a8c4432837", cerName: "cdaps")
//        #else
//            #if DEBUG
//                NIMSDK.shared().register(withAppID: "010d0e7d80993a4f353e69a8c4432837", cerName: "cdapsdev")
//            #else
//                NIMSDK.shared().register(withAppID: "010d0e7d80993a4f353e69a8c4432837", cerName: "cdaps")
//            #endif
//        #endif
//        
//        // 注册云信自定义消息解释器
//        NIMCustomObject.registerCustomDecoder(CDCustomAttachmentDecoder())
//        NIMKit.shared().registerLayoutConfig(CDIMCellLayoutConfig())
//        
////        restAudioSessionSetting()
//        
//        NIMSDK.shared().loginManager.add(self)
//        NIMAVChatSDK.shared().netCallManager.add(self)
//        NIMSDK.shared().systemNotificationManager.add(self)
//        NotificationCenter.default.addObserver(self, selector: #selector(userDidSignup), name: NSNotification.Name.CDUserSignupSuccess, object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(userDidLogin), name: NSNotification.Name.CDUserLoginSuccess, object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(helpUserLogout), name: NSNotification.Name.CDContactNeedLogoutNotificationKey, object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate), name: Notification.Name.UIApplicationWillTerminate, object: nil)
//        
//        
//        if let userID = MyselfSingleton.shared.userInfo?.userID,!userID.isEmpty {
//            login(userName: userID, autoLogin: true)
//        }
//    }
//    
//    
//    //MARK: Private
//    func restAudioSessionSetting() {
//        UIApplication.shared.beginReceivingRemoteControlEvents()
//        do{
//            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.defaultToSpeaker)
//        }
//        catch{
//            CDUtility.log("AVAudioSession Error:\(error)")
//        }
//        do{
//            try AVAudioSession.sharedInstance().setActive(true)
//        }
//        catch{
//            CDUtility.log("AVAudioSession Error:\(error)")
//        }
//    }
//    
//    func login(userName: String,autoLogin: Bool) {
//        guard let token = MyselfSingleton.shared.config?.chatToken else {
//            return
//        }
//        if autoLogin
//        {
//            let data = NIMAutoLoginData()
//            data.account = userName
//            data.token = token
//            data.forcedMode = false
//            NIMSDK.shared().loginManager.autoLogin(data)
//        }
//        else{
//            NotificationCenter.default.post(name: NSNotification.Name.CDContactsNeedRefreshKey, object: nil)
//            NIMSDK.shared().loginManager.login(userName, token: token) {[weak self] (nimError) in
//                if let strongSelf = self{
//                    if nimError != nil{
//                        let error = nimError! as NSError
//                        if error.code == 301 || error.code == 422 // 被封禁 禁用
//                        {
//                            strongSelf.didRemoveFromServer()
//                            return
//                        }
//                    }
//                }
//            }
//        }
//        UIManager.shared.startHomepageDataRefreshLoop()
//    }
//    
//    func updateApnsSetting() {
//        guard let config = MyselfSingleton.shared.config else { return  }
//        let setting = NIMPushNotificationSetting()
//        setting.type = config.previewNotifyDetail == "1" ? .detail : .noDetail
//        setting.noDisturbing = config.isEnableNotifications == "1" ? false : true
//        setting.noDisturbingStartM = 0
//        setting.noDisturbingStartH = 0
//        setting.noDisturbingEndH = UInt.max
//        setting.noDisturbingEndM = 60
//        NIMSDK.shared().apnsManager.updateApnsSetting(setting) { (error) in
//            if error != nil{
//                CDUtility.log("NIMSDK.shared().apnsManager.updateApnsSettingFailed:\(error!.localizedDescription)")
//            }
//        }
//        // 向云信注册其他第三方未读消息的数量,云信会自动访问里面的回调
//        NIMSDK.shared().apnsManager.registerBadgeCountHandler { () -> UInt in
//            return UInt(self.unreadCount() + CDPushService.shared.unreadCount)
//        }
//        // 向极光设置和通知消息未读数，极光不会自动获取，需要在用户登录，收到im消息，收到极光推送，通讯录拉到未读数，已经用户登出时候设置
//        CDPushService.shared.configUnreadCount(CDPushService.shared.unreadCount)
//    }
//    
//    func registerDeviceToken(_ deviceToken: Data){
//        NIMSDK.shared().updateApnsToken(deviceToken)
//    }
//    
//    // 用户登出
//    func userLogout() {
//        guard !NIMSDK.shared().loginManager.currentAccount().isEmpty else { // 为空代表已经登出了，重复登出会导致logout的error，然后makeToast"请求过程超时"
//            return
//        }
//        MyselfSingleton.shared.logOutcClean()
//        NIMSDK.shared().loginManager.logout { (error) in
//            if error != nil{
//                let e = error! as NSError
//                if e.code != NIMRemoteErrorCode.codeTimeoutError.rawValue // 超时
//                {
//                    CDUtility.log(error!.localizedDescription)
//                    UIManager.shared.tabBarController.makeToast(error!.localizedDescription)
//                }
//            }
//            self.imLogOut()
//        }
//    }
//    
//    // 登出后的操作
//    func imLogOut() {
//        CDPushService.shared.cleanTagsAndAlias()
//        CDPushService.shared.unreadCount = 0
//        CDPushService.shared.configUnreadCount(0)
//        currentNetCallID = 0
//        UIApplication.shared.applicationIconBadgeNumber = 0
//        if let nav = UIManager.shared.tabBarController.selectedViewController as? UINavigationController
//        {
//            nav.popToRootViewController(animated: false)
//        }
//        UIManager.shared.tabBarController.showLoginViewController()
//        UIManager.shared.tabBarController.selectedIndex = TabBarIndex.homePage.rawValue
//    }
//    
//    func unreadCount() -> Int {
//        return NIMSDK.shared().conversationManager.allUnreadCount()
//    }
//    
//    func didRemoveFromServer() {
//        UIManager.shared.shouldShowKickedAlert = true
//        UIManager.shared.kickedMessage = "您的账号被解除，请联系客服"
//        userLogout()
//    }
//    
//}
//
//extension CDIMService{
//    
//    //MARK: Session Operation
//    
//    func afterDeleteFriendCleanSession(_ sessionID: String) {
//        let session = NIMSession(sessionID, type: .P2P)
//        let option = NIMDeleteMessagesOption()
//        option.removeSession = true
//        option.removeTable = true
//        NIMSDK.shared().conversationManager.deleteAllmessages(in: session, option: option)
//    }
//    
//    func sendDeleteFriendCustonNotification(_ sessionID: String) {
//        // 删除好友后通知对方尽快删除会话调用afterDeleteFriendCleanSession
//        guard let myID = MyselfSingleton.shared.userInfo?.userID else {
//            return
//        }
//        
//        let data = ["userID" : myID]
//        let dictionary = ["type" : CDIMCustomNotificationTypeDeleteFriend,
//                          "data" : data] as [String : Any]
//        let jsonString = dictionary.convertToJsonString()
//        
//        let sesssion = NIMSession(sessionID, type: .P2P)
//        let setting = NIMCustomSystemNotificationSetting()
//        setting.apnsEnabled = false
//        setting.apnsWithPrefix = false
//        setting.shouldBeCounted = false
//        let customNotification = NIMCustomSystemNotification(content: jsonString)
//        customNotification.sendToOnlineUsersOnly = true
//        customNotification.setting = setting
//        NIMSDK.shared().systemNotificationManager.sendCustomNotification(customNotification,
//                                                                         to: sesssion) { (error) in
//                                                                            if error != nil
//                                                                            {
//                                                                                CDUtility.log("云信自定义系统消息发送失败：\(error!.localizedDescription)")
//                                                                            }
//        }
//    }
//    
//    //MARK: SystemNotification
//    func applicationWillTerminate() {
//        if currentNetCallID != 0
//        {
//            NIMAVChatSDK.shared().netCallManager.hangup(currentNetCallID)
//            currentNetCallID = 0
//        }
//    }
//    
//    // Notification
//    func userDidSignup() {
//        login(userName: (MyselfSingleton.shared.userInfo?.userID)!, autoLogin: false)
//        UIManager.shared.tabBarController.reloadRedPoint()
//    }
//    
//    func userDidLogin() {
//        login(userName: (MyselfSingleton.shared.userInfo?.userID)!, autoLogin: false)
//        UIManager.shared.tabBarController.reloadRedPoint()
//    }
//    
//    func helpUserLogout() {
//        userLogout()
//    }
//    
//}
//
////MARK: NIMSystemNotificationManagerDelegate
//extension CDIMService : NIMSystemNotificationManagerDelegate
//{
//    //MARK: 推送
//    
//    func onSystemNotificationCountChanged(_ unreadCount: Int) {
//        CDUtility.log("云信系统通知未读数量：\(unreadCount)")
//    }
//    
//    // 云信内置的系统通知的回调(群消息+添加好友)我们用不到
//    func onReceive(_ notification: NIMSystemNotification) {
//        CDUtility.log(notification)
//    }
//    
//    func onReceive(_ notification: NIMCustomSystemNotification) {
//        if let data = notification.content?.data(using: String.Encoding.utf8)
//        {
//            if let dict = (try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String : Any]
//            {
//                guard let type = dict["type"] as? String else{
//                    return
//                }
//                if type == CDIMCustomNotificationTypeDeleteFriend
//                {
//                    if let sender = notification.sender,!sender.isEmpty
//                    {
//                        afterDeleteFriendCleanSession(sender)
//                        if let currentViewController = CDUtility.currentViewController() as? MessageViewController
//                        {
//                            currentViewController.makeToast("对方已和你解除好友关系", durations: ToasterDelay.long)
//                            currentViewController.navigationController?.popViewController(animated: true)
//                        }
//                    }
//                }
//            }
//        }
////        CDUtility.log(notification.content)
//    }
//}
//
////MARK: NIMNetCallManagerDelegate
//extension CDIMService : NIMNetCallManagerDelegate
//{
//    func onReceive(_ callID: UInt64, from caller: String, type: NIMNetCallMediaType, message extendMessage: String?) {
//        if currentNetCallID != 0
//        {
//            if callID != currentNetCallID{
//                NIMAVChatSDK.shared().netCallManager.control(callID, type: NIMNetCallControlType.busyLine)
//                return
//            }
//            return
//        }
//        
//        
//        guard let vc = CDUtility.currentViewController() else{
//            return
//        }
//        if let _ = vc.navigationController as? LoginNavigationController
//        {
//            return
//        }
//        
//        if UIManager.shared.tabBarController.currentNavigationController() == nil
//        {
//            vc.dismiss(animated: true, completion: {
//                self.onReceive(callID, from: caller, type: type, message: extendMessage)
//            })
//            return
//        }
//        
//        
//        guard let _ = UIManager.shared.tabBarController.currentNavigationController() else{
//            return
//        }
//        
//        guard let id = MyselfSingleton.shared.userInfo?.userID else{
//            return
//        }
//        let api = CDRequestAPI.getSimpleUserProfile(ShowHudKey: false, myID: id, userID: caller)
//        CDNetWorkService.requestDataWithTarget(target: api, type: UserLite.self, successClosure: { [weak self] (obj, code, message) in
//            if let _ = self{
//                var name = ""
//                var avatar = ""
//                if code == 10
//                {
//                    if let model = obj as? UserLite
//                    {
//                        if let state = DateRequestState(rawValue: model.dateState), (state == .done || state == .helper)
//                        {
//                            name = model.nickName
//                            avatar = model.avatar
//                            var viewController = UIViewController()
//                            switch type {
//                            case .video:
//                                viewController = NetCallVideoChatViewController(me: caller, callId: callID, nick: name, avatar: avatar)
//                            default:
//                                viewController = NetCallAudioChatViewController(me: caller, callId: callID, nick: name, avatar: avatar)
//                            }
//                            let navi = UINavigationController(rootViewController: viewController)
//                            navi.isNavigationBarHidden = true
//                            vc.present(navi, animated: true, completion: nil)
//                        }
//                    }
//                }
//                else
//                {
//                    CDUtility.log(message)
//                }
//                
////                let transition = CATransition.init()
////                transition.duration = 0.25
////                transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
////                transition.type = kCATransitionPush
////                transition.subtype = kCATransitionFromTop
////                viewController.hidesBottomBarWhenPushed = true
////                navi.view.layer.add(transition, forKey: nil)
////                navi.isNavigationBarHidden = true
////                navi.pushViewController(viewController, animated: false)
//            }
//        }) { (msg) in
//            CDUtility.log(msg)
//        }
//    }
//    
//}
//
////MARK: NIMLoginManagerDelegate
//extension CDIMService : NIMLoginManagerDelegate{
//
//    func onLogin(_ step: NIMLoginStep) {
//        if step == .loginOK
//        {
//            updateApnsSetting()
//        }
//    }
//    
//    func onAutoLoginFailed(_ error: Error) {
//        let e = error as NSError
//        if e.code == NIMRemoteErrorCode.codeExist.rawValue // app在杀死的时候账号被顶掉
//        {
//            UIManager.shared.shouldShowKickedAlert = true
//            UIManager.shared.kickedMessage = "您的账号在其他设备登录，如果这不是您本人的操作，请注意账号安全。"
//        }
//        if e.code == NIMRemoteErrorCode.codeInvalidPass.rawValue || e.code == NIMRemoteErrorCode.codeExist.rawValue || e.code == NIMRemoteErrorCode.accountBlock.rawValue
//        {
//            userLogout()
//        }
//    }
//    
//    func onKick(_ code: NIMKickReason, clientType: NIMLoginClientType) {
//        var reason = "您被踢下线"
//        switch (code)
//        {
//        case .byClient,.byClientManually:
//            reason = "您的账号在其他设备登录，如果这不是您本人的操作，请注意账号安全。"
//        case .byServer:
//            reason = "您被服务器踢下线"
//        }
//        UIManager.shared.shouldShowKickedAlert = true
//        UIManager.shared.kickedMessage = reason
//        userLogout()
//    }
//    
//}
